from flask import Flask, render_template, request, jsonify

app = Flask(__name__)

# 主页路由\@app.route('/')
def index():
    return render_template('index.html')

# 计算API路由\@app.route('/calculate', methods=['POST'])
def calculate():
    try:
        # 获取请求数据
        data = request.json
        num1 = float(data.get('num1'))
        num2 = float(data.get('num2'))
        operator = data.get('operator')
        
        # 执行计算
        result = 0
        if operator == '+':
            result = num1 + num2
        elif operator == '-':
            result = num1 - num2
        elif operator == '*':
            result = num1 * num2
        elif operator == '/':
            if num2 == 0:
                return jsonify({'error': '除数不能为零！'})
            result = num1 / num2
        else:
            return jsonify({'error': '不支持的运算符！'})
        
        # 返回结果
        return jsonify({'result': result})
    except Exception as e:
        return jsonify({'error': str(e)})

if __name__ == '__main__':
    print('简易计算器应用已启动！访问 http://localhost:5000 开始使用。')
    app.run(debug=True)